package com.sumer.psychology.blog.infrastructure.persistence.mongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.sumer.psychology.blog.domain.model.BlogAvailability;
import com.sumer.psychology.common.persistence.mongodb.AbstractMongoRepository;

/**
 * blog mongodb
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/29
 * Time: 16:06
 */
public class MongoBlogRepository extends AbstractMongoRepository {
    private static final String DB_NAME = "sumer_blog";
    private static final String BLOG_KEY = "blogId.identity";

    /**
     * 添加Blog
     *
     * @param data json
     */
    public void add(String data) {
        DBObject blog = initializeCreateData(data, BLOG_KEY);
        blog.put("availability", "ACTIVE");
        blog.put("views", 0);
        blog.put("replies", 0);

        db().getCollection(DB_NAME).insert(blog);
    }

    /**
     * 查询唯一blog
     *
     * @param blogId id
     * @param availability availability
     * @return blog
     */
    public DBObject findOne(String blogId, BlogAvailability availability) {
        DBObject queryBlog = idCondition(blogId);
        queryBlog.put("availability", availability.toString());

        return db().getCollection(DB_NAME).findOne(queryBlog);
    }

    /**
     * 修改Blog
     *
     * @param data json
     */
    public void change(String data) {
        change(data, null);
    }

    /**
     * 修改Blog
     *
     * @param data         json
     * @param availability status
     */
    public void change(String data, BlogAvailability availability) {
        DBObject changedBlog = initializeData(data, BLOG_KEY);
        if (availability != null) {
            changedBlog.put("availability", availability.toString());
        }

        change(changedBlog);
    }

    /*
     * 根据object修改
     */
    private void change(DBObject changedBlog) {
        DBObject queryBlog = idCondition((String) changedBlog.get("_id"));

        db().getCollection(DB_NAME).update(
                queryBlog,
                new BasicDBObject("$set", changedBlog),
                true, // upsert
                false);
    }

    @Override
    protected String dbName() {
        return DB_NAME;
    }

}
